<template>
  <a-card :body-style="{ height: 'calc(100vh - 125px)' }">
    <!-- 数据列表 -->
    <a-row
      class="w-full h-full flex flex-col overflow-x-auto overflow-y-hidden"
    >
      <!-- 查询条件 -->
      <a-row v-if="showSearchRow" class="w-full">
        <a-form
          :model="searchForm"
          label-align="left"
          layout="inline"
          size="small"
        >
          <a-form-item field="priceType" label="价格类型">
            <a-select
              v-model="searchForm.priceType"
              allow-clear
              placeholder="价格类型"
            >
              <a-option
                v-for="(d, index) in dicts[proxy.DICT.lindiPriceType]"
                :key="index"
                :label="d.dictValue"
                :value="d.dictKey"
              />
            </a-select>
          </a-form-item>

          <a-form-item field="effectiveDate" label="生效日期">
            <a-range-picker
              v-model="searchForm.effectiveDateRange"
              format="YYYY-MM-DD HH:mm:ss"
              show-time
            />
          </a-form-item>
        </a-form>
        <a-row class="w-full mt-2" justify="center">
          <a-space>
            <a-button type="primary" @click="getPageList(false)">
              <template #icon>
                <icon-search />
              </template>
              <template #default>查询</template>
            </a-button>
            <a-popconfirm
              :popup-visible="deleteConfirmVisible"
              content="确定删除选中价格配置吗?"
              type="warning"
              @cancel="onDeleteConfirmCancel"
              @ok="onDeleteConfirmOK"
            >
              <a-button
                status="danger"
                type="primary"
                @click="deleteBtnClick(selectedKeys)"
                v-perm="['lindi:priceConfig:delete']"
              >
                <template #icon>
                  <icon-delete />
                </template>
                <template #default>删除</template>
              </a-button>
            </a-popconfirm>
            <a-button @click="getPageList(true)">
              <template #icon>
                <icon-sync />
              </template>
              <template #default>重置</template>
            </a-button>
          </a-space>
        </a-row>
      </a-row>

      <!-- 分割线 -->
      <a-divider v-if="showSearchRow" class="mt-2" />

      <!-- 数据操作区 -->
      <a-row class="w-full flex justify-between">
        <a-space>
          <!-- 添加 -->
          <a-button
            size="small"
            type="primary"
            @click="addBtnClick()"
            v-perm="['lindi:priceConfig:add']"
          >
            <template #icon>
              <icon-plus />
            </template>
            <template #default>添加</template>
          </a-button>
        </a-space>
        <a-space>
          <!-- 刷新 -->
          <a-button shape="circle" size="small" @click="getPageList(false)">
            <template #icon>
              <icon-refresh />
            </template>
          </a-button>
          <!-- 收缩/展开 -->
          <a-button
            shape="circle"
            size="small"
            @click="showSearchRow = !showSearchRow"
          >
            <template #icon>
              <icon-caret-up v-if="showSearchRow" />
              <icon-caret-down v-else />
            </template>
          </a-button>
        </a-space>
      </a-row>

      <!-- 数据展示区 -->
      <a-row class="w-full flex-1 mt-3 overflow-y-auto">
        <a-table
          v-model:selectedKeys="selectedKeys"
          :columns="datatable.columns"
          :data="datatable.records"
          :loading="datatable.loading"
          :pagination="false"
          :row-selection="rowSelection"
          :scroll="{ minWidth: 800, y: '100%' }"
          class="w-[100%]"
          row-key="priceConfigId"
          table-layout-fixed
        >
          <!-- 价格名称 -->
          <template #priceName="{ record }">
            <a-button
              type="text"
              class="text-blue-600 font-medium"
              @click="detailBtnClick(record.priceConfigId)"
              v-perm="['lindi:priceConfig:get']"
            >
              {{ record.priceName }}
            </a-button>
          </template>
          <!-- 价格类型 -->
          <template #priceType="{ record }">
            <dict-convert
              :dict-data="dicts[proxy.DICT.lindiPriceType]"
              :dict-key="String(record.priceType)"
            />
          </template>
          <!-- 单价 -->
          <template #unitPrice="{ record }">
            <span class="font-medium text-blue-600">
              {{ record.unitPrice }}万元/亩
            </span>
          </template>

          <!-- 操作 -->
          <template #operation="{ record }">
            <a-space>
              <a-button
                size="mini"
                type="text"
                @click="editBtnClick(record.priceConfigId)"
                v-perm="['lindi:priceConfig:update']"
              >
                <template #icon>
                  <icon-edit />
                </template>
                <template #default>编辑</template>
              </a-button>
              <a-popconfirm
                content="确认要删除吗?"
                @ok="deleteBtnOkClick(record.priceConfigId)"
              >
                <a-button
                  size="mini"
                  status="danger"
                  type="text"
                  v-perm="['lindi:priceConfig:delete']"
                >
                  <template #icon>
                    <icon-delete />
                  </template>
                  <template #default>删除</template>
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </a-table>
      </a-row>

      <!-- 分页 -->
      <a-row class="w-full flex justify-end mt-2">
        <pagination
          v-if="datatable.total > 0"
          v-model:page-num="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :total="datatable.total"
          @pagination="getPageList(false)"
        />
      </a-row>
    </a-row>

    <a-modal
      v-model:visible="modal.visible"
      :esc-to-close="false"
      :footer="false"
      :mask-closable="false"
      :width="modal.width"
      draggable
    >
      <template #title>{{ modal.title }}</template>
      <component
        :is="modal.component"
        v-if="modal.visible"
        :params="modal.params"
        @cancel="onCancel"
        @ok="onOk"
      />
    </a-modal>
  </a-card>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, shallowRef, onMounted } from "vue";
import { Message } from "@arco-design/web-vue";
import { useRouter } from "vue-router";
import Pagination from "~/components/pagination/index.vue";
import PriceDetail from "~/pages/lindi/price/PriceDetail.vue";
import PriceEdit from "~/pages/lindi/price/PriceEdit.vue";
import {
  addPriceConfigApi,
  deletePriceConfigByPriceConfigIdApi,
  updatePriceConfigByPriceConfigIdApi,
  getPagePriceConfigListApi,
  getPriceConfigByPriceConfigIdApi,
} from "~/api/lindi/priceConfig";

//路由实例
const router = useRouter();

//全局实例
const { proxy } = getCurrentInstance();
//加载字典
const dicts = proxy.LoadDicts([proxy.DICT.lindiPriceType]);

//是否展示搜索区域
const showSearchRow = ref(true);
//搜索参数表单
const searchForm = reactive({
  //价格类型
  priceType: null,
  //生效日期范围
  effectiveDateRange: null,
  //页码
  pageNum: 1,
  //条数
  pageSize: 10,
});
//表格选中数据
const selectedKeys = ref([]);
//表格选中
const rowSelection = reactive({
  type: "checkbox",
  showCheckedAll: true,
  onlyCurrent: true,
});
//数据列表
const datatable = reactive({
  //列配置
  columns: [
    {
      title: "价格名称",
      dataIndex: "priceName",
      slotName: "priceName",
      align: "center",
      width: 200,
    },
    {
      title: "价格类型",
      dataIndex: "priceType",
      slotName: "priceType",
      align: "center",
      width: 150,
    },
    {
      title: "单价(万元/亩)",
      dataIndex: "unitPrice",
      slotName: "unitPrice",
      align: "center",
      width: 150,
    },
    {
      title: "生效时间",
      dataIndex: "effectiveDate",
      align: "center",
      width: 160,
    },
    {
      title: "失效时间",
      dataIndex: "expireTime",
      align: "center",
      width: 160,
      render: ({ record }) => {
        return record.expireTime || "-";
      },
    },
    {
      title: "备注说明",
      dataIndex: "remark",
      align: "center",
      width: 200,
      ellipsis: true,
      tooltip: true,
    },
    // {
    //   title: "创建时间",
    //   dataIndex: "createTime",
    //   align: "center",
    //   width: 150,
    // },
    {
      title: "操作",
      slotName: "operation",
      align: "center",
      width: 150,
      fixed: "right",
    },
  ],
  //加载
  loading: false,
  //数据列表
  records: [],
  //总条数
  total: 0,
});

//查询数据列表
const getPageList = (isReset = false) => {
  if (isReset) {
    searchForm.priceType = null;
    searchForm.effectiveDateRange = null;
    searchForm.pageNum = 1;
    searchForm.pageSize = 10;
  }
  datatable.loading = true;

  const queryData = {
    pageNum: searchForm.pageNum,
    pageSize: searchForm.pageSize,
    priceType: searchForm.priceType,
    effectiveDateStart: searchForm.effectiveDateRange?.[0],
    effectiveDateEnd: searchForm.effectiveDateRange?.[1],
  };

  getPagePriceConfigListApi(queryData)
    .then((response) => {
      datatable.records = response.records || [];
      datatable.total = response.total || 0;
      console.log("datatable.records", datatable.records);
    })
    .catch((error) => {
      console.error("获取价格配置列表失败:", error);
      proxy.$msg.error("获取数据失败");
    })
    .finally(() => {
      datatable.loading = false;
    });
};

//公共模态框
const modal = reactive({
  //是否显示
  visible: false,
  //模态框标题
  title: "林地价格管理",
  //宽度
  width: "800px",
  //传递参数
  params: {},
  //组件名称
  component: null,
});

//添加按钮 -> 点击事件
const addBtnClick = () => {
  modal.visible = true;
  modal.title = "新增价格配置";
  modal.width = "1000px";
  modal.params = { operationType: proxy.operationType.add.type };
  modal.component = shallowRef(PriceEdit);
};

//编辑按钮 -> 点击事件
const editBtnClick = (priceConfigId) => {
  modal.visible = true;
  modal.title = "编辑价格配置";
  modal.width = "1000px";
  modal.params = {
    operationType: proxy.operationType.update.type,
    priceConfigId: priceConfigId,
  };
  modal.component = shallowRef(PriceEdit);
};

//详情按钮 -> 点击事件
const detailBtnClick = (priceConfigId) => {
  modal.visible = true;
  modal.title = "林地价格详细信息";
  modal.width = "1000px";
  modal.params = {
    operationType: proxy.operationType.detail.type,
    priceConfigId: priceConfigId,
  };
  modal.component = shallowRef(PriceDetail);
};

// 删除确认弹窗
const deleteConfirmVisible = ref(false);

//删除按钮 -> 点击事件
const deleteBtnClick = (keys) => {
  if (!keys || keys.length === 0) {
    proxy.$msg.warning("请选择要删除的数据");
    return;
  }
  deleteConfirmVisible.value = true;
};

//删除确认 -> 取消
const onDeleteConfirmCancel = () => {
  deleteConfirmVisible.value = false;
};

//删除确认 -> 确定
const onDeleteConfirmOK = () => {
  deleteConfirmVisible.value = false;

  const deletePromises = selectedKeys.value.map((id) =>
    deletePriceConfigByPriceConfigIdApi(id)
  );

  Promise.all(deletePromises)
    .then((responses) => {
      const allSuccess = responses.every((response) => response);
      if (allSuccess) {
        proxy.$msg.success("批量删除成功");
        selectedKeys.value = [];
        getPageList(false);
      } else {
        proxy.$msg.error("部分删除失败");
      }
    })
    .catch((error) => {
      console.error("批量删除价格配置失败:", error);
      proxy.$msg.error("批量删除失败");
    });
};

//删除单个 -> 确定
const deleteBtnOkClick = (priceConfigId) => {
  deletePriceConfigByPriceConfigIdApi(priceConfigId)
    .then((response) => {
      proxy.$msg.success("删除价格配置成功");
      getPageList(false);
    })
    .catch((error) => {
      console.error("删除价格配置失败:", error);
      proxy.$msg.error("删除失败");
    });
};

//模态框取消
const onCancel = () => {
  modal.visible = false;
};

//模态框确定
const onOk = () => {
  modal.visible = false;
  getPageList(false);
};

//页面加载时获取数据
onMounted(() => {
  getPageList(false);
});
</script>

<style scoped>
.font-medium {
  font-weight: 500;
}

.text-blue-600 {
  color: #2563eb;
}

.text-green-600 {
  color: #16a34a;
}

.text-red-600 {
  color: #dc2626;
}

.text-gray-500 {
  color: #6b7280;
}

.text-sm {
  font-size: 0.875rem;
  line-height: 1.25rem;
}
</style>
